package com.zxh.project.areachooseapplication;

import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetManager;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import kankan.wheel.widget.OnWheelChangedListener;
import kankan.wheel.widget.WheelView;
import kankan.wheel.widget.adapters.ArrayWheelAdapter;
import kankan.wheel.widget.interfaces.XmlParserHandler;
import kankan.wheel.widget.interfaces.model.CityModel;
import kankan.wheel.widget.interfaces.model.DistrictModel;
import kankan.wheel.widget.interfaces.model.ProvinceModel;


public class MainActivity extends AppCompatActivity implements OnWheelChangedListener {

    private TextView areaTv;
    private ImageView iv_all;
    private static PopupWindow mPopTime,mPop;
    private View mAreaPicker;
    private WheelView mViewProvince,mViewCity,mViewDistrict;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initAreaView();
        iv_all = ((ImageView) findViewById(R.id.iv_all));
        areaTv = ((TextView) findViewById(R.id.areaTv));
        findViewById(R.id.btnJson).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(MainActivity.this,MainJsonActivity.class));
            }
        });
        findViewById(R.id.chooseLinear).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                propetyAnim(iv_all);
                showTimePicker(view, mAreaPicker,MainActivity.this,iv_all);
            }
        });
        findViewById(R.id.btn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(MainActivity.this,Main2Activity.class));
            }
        });
    }


    private void initAreaView() {
        initAreaPicker();
        initProvinceDatas();
        mViewProvince.setViewAdapter(new ArrayWheelAdapter<>(this, mProvinceDatas,15,14));

        updateCities();
        updateAreas();
    }

    private void updateAreas() {
        int pCurrent = this.mViewCity.getCurrentItem();
        this.mCurrentCityName = ((String[])this.mCitisDatasMap.get(this.mCurrentProviceName))[pCurrent];
        String[] areas = (String[])this.mDistrictDatasMap.get(this.mCurrentCityName);
        if(areas == null) {
            areas = new String[]{""};
        }

        this.mViewDistrict.setViewAdapter(new ArrayWheelAdapter(this, areas,15,14));
        this.mViewDistrict.setCurrentItem(0);
    }

    private void updateCities() {
        int pCurrent = this.mViewProvince.getCurrentItem();
        this.mCurrentProviceName = this.mProvinceDatas[pCurrent];
        String[] cities = (String[])this.mCitisDatasMap.get(this.mCurrentProviceName);
        if(cities == null) {
            cities = new String[]{""};
        }

        this.mViewCity.setViewAdapter(new ArrayWheelAdapter(this, cities,15,14));
        this.mViewCity.setCurrentItem(0);
        this.updateAreas();
    }

    private void initAreaPicker() {
        mAreaPicker = View.inflate(this,R.layout.picker_area_layout,null);
        mViewProvince = ((WheelView) mAreaPicker.findViewById(R.id.id_province));
        mViewCity = ((WheelView) mAreaPicker.findViewById(R.id.id_city));
        mViewDistrict = ((WheelView) mAreaPicker.findViewById(R.id.id_area));
        mViewProvince.setVisibleItems(7);
        mViewCity.setVisibleItems(7);
        mViewDistrict.setVisibleItems(7);
        mViewProvince.addChangingListener(this);
        mViewCity.addChangingListener(this);
        mViewDistrict.addChangingListener(this);

        RelativeLayout tv_cancelStart = ((RelativeLayout) mAreaPicker.findViewById(R.id.tv_cancel));
        RelativeLayout tv_confirmStart = ((RelativeLayout) mAreaPicker.findViewById(R.id.tv_confirm));
        tv_cancelStart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mPopTime != null){
                    mPopTime.dismiss();
                }
            }
        });
        tv_confirmStart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                currentProPosition = newProPosition;
                currentCityPosition = newCityPosition;
                currentDisPosition = newDisPosition;
                MainActivity.this.mCurrentProviceName = mProvinceDatas[currentProPosition];
                MainActivity.this.mCurrentCityName = ((String[])MainActivity.this.mCitisDatasMap.get(MainActivity.this.mCurrentProviceName))[currentCityPosition];
                String[] disNames = ((String[])MainActivity.this.mDistrictDatasMap.get(MainActivity.this.mCurrentCityName));
                if(disNames!=null && disNames.length > currentDisPosition){
                    MainActivity.this.mCurrentDistrictName = disNames[currentDisPosition];
                }else{
                    mCurrentDistrictName = "";
                }
                areaTv.setText(mCurrentProviceName+"  "+mCurrentCityName+"  "+mCurrentDistrictName);

                if (mPopTime != null){
                    mPopTime.dismiss();
                }
            }
        });
    }
    protected void initProvinceDatas() {
        List provinceList = null;
        AssetManager asset = this.getAssets();

        try {
            InputStream e = asset.open("province_data.xml");
            SAXParserFactory spf = SAXParserFactory.newInstance();
            SAXParser parser = spf.newSAXParser();
            XmlParserHandler handler = new XmlParserHandler();
            parser.parse(e, handler);
            e.close();
            provinceList = handler.getDataList();
            List cityList;
            if(provinceList != null && !provinceList.isEmpty()) {
                this.mCurrentProviceName = ((ProvinceModel)provinceList.get(0)).getName();
                List i = ((ProvinceModel)provinceList.get(0)).getCityList();
                if(i != null && !i.isEmpty()) {
                    this.mCurrentCityName = ((CityModel)i.get(0)).getName();
                    cityList = ((CityModel)i.get(0)).getDistrictList();
                    this.mCurrentDistrictName = ((DistrictModel)cityList.get(0)).getName();
                    this.mCurrentZipCode = ((DistrictModel)cityList.get(0)).getZipcode();
                }
            }

            this.mProvinceDatas = new String[provinceList.size()];
            this.proAreaIds = new String[provinceList.size()];

            for(int var17 = 0; var17 < provinceList.size(); ++var17) {
                this.mProvinceDatas[var17] = ((ProvinceModel)provinceList.get(var17)).getName();
                this.proAreaIds[var17] = ((ProvinceModel) provinceList.get(var17)).getArea_id();
                cityList = ((ProvinceModel)provinceList.get(var17)).getCityList();
                String[] cityNames = new String[cityList.size()];
                String[] cityAreaIds = new String[cityList.size()];

                for(int j = 0; j < cityList.size(); ++j) {
                    cityNames[j] = ((CityModel)cityList.get(j)).getName();
                    cityAreaIds[j]=((CityModel) cityList.get(j)).getArea_id();
                    List districtList = ((CityModel)cityList.get(j)).getDistrictList();
                    String[] distrinctNameArray = new String[districtList.size()];
                    String[] distrinctAreaId = new String[districtList.size()];
                    DistrictModel[] distrinctArray = new DistrictModel[districtList.size()];

                    for(int k = 0; k < districtList.size(); ++k) {
                        DistrictModel districtModel = new DistrictModel(((DistrictModel)districtList.get(k)).getName(), ((DistrictModel)districtList.get(k)).getZipcode(),((DistrictModel)districtList.get(k)).getArea_id());
                        this.mZipcodeDatasMap.put(((DistrictModel)districtList.get(k)).getName(), ((DistrictModel)districtList.get(k)).getZipcode());
                        distrinctArray[k] = districtModel;
                        distrinctNameArray[k] = districtModel.getName();
                        distrinctAreaId[k] = districtModel.getArea_id();
                    }
                    this.mDistrictDatasMap.put(cityNames[j], distrinctNameArray);
                    this.distAreaIdMap.put(cityNames[j],distrinctAreaId);
                }

                this.mCitisDatasMap.put(((ProvinceModel)provinceList.get(var17)).getName(), cityNames);
                this.cityAreaIdMap.put(((ProvinceModel) provinceList.get(var17)).getName(),cityAreaIds);
            }
        } catch (Throwable var16) {
            var16.printStackTrace();
        }
    }

    /**
     半透明背景出现的动画
     */
    private void propetyAnim(ImageView iv) {
        ObjectAnimator animator = ObjectAnimator.ofFloat(iv, "alpha", 0, 0.2f, 0.5f, 0.7f, 0.9f, 1);
        animator.setDuration(500);
        animator.setRepeatCount(0);
        animator.start();
        iv.setVisibility(View.VISIBLE);
    }
    public static void showTimePicker(View parent, final View view, final Context context, final ImageView iv_all) {
        mPopTime = new PopupWindow(view,
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);

        mPopTime.setOutsideTouchable(true);
        mPopTime.setFocusable(true); // 这个很重要,涉及返回键能否取消mPop！
        mPopTime.setBackgroundDrawable(new ColorDrawable(0));
        //mPop.setAnimationStyle(R.style.AndroidImageSlider_Attractive_Rect_Blue);
        mPopTime.setAnimationStyle(R.style.AnimBottom);
        mPopTime.showAtLocation(parent, Gravity.BOTTOM, 0,0);
        mPopTime.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                propetyAnim2(iv_all);
                mPopTime = null;

            }
        });

        // 重写onKeyListener
        view.setOnKeyListener(new View.OnKeyListener() {

            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK) {
                    //mPop.dismiss();
                    return true;
                }
                return true;
            }
        });

        // 点击其他地方消失
        view.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                // TODO Auto-generated method stub
                if (mPop != null && mPop.isShowing()) {


                }
                return false;
            }
        });
        mPopTime.showAsDropDown(parent);
    }
    /**
     * 半透明背景消失的动画
     * @param iv
     */
    public static void propetyAnim2(final ImageView iv){
        ObjectAnimator animator = ObjectAnimator.ofFloat(iv,"alpha",1,0.9f,0.7f,0.5f,0.2f,0);
        animator.setDuration(500);
        animator.setRepeatCount(0);
        animator.start();
        animator.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {

            }

            @Override
            public void onAnimationEnd(Animator animation) {
                iv.setVisibility(View.GONE);
            }

            @Override
            public void onAnimationCancel(Animator animation) {

            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        });
    }

    protected String[] mProvinceDatas,proAreaIds;
    protected Map<String, String[]> mCitisDatasMap = new HashMap(),cityAreaIdMap = new HashMap<>();
    protected Map<String, String[]> mDistrictDatasMap = new HashMap(),distAreaIdMap = new HashMap<>();
    protected Map<String, String> mZipcodeDatasMap = new HashMap();
    protected String mCurrentProviceName;
    protected String mCurrentCityName;
    protected String mCurrentDistrictName = "";
    protected String mCurrentZipCode = "";
    private int currentProPosition,currentCityPosition,currentDisPosition;
    private int newProPosition,newCityPosition,newDisPosition;
    private int mDistrictPosition;
    @Override
    public void onChanged(WheelView wheel, int oldValue, int newValue) {
        if(wheel == this.mViewProvince) {
            newProPosition = newValue;
            mDistrictPosition = 0;
            this.updateCities();
        } else if(wheel == this.mViewCity) {
            newCityPosition = newValue;
            this.updateAreas();
            mDistrictPosition = 0;
        } else if(wheel == this.mViewDistrict) {
            mDistrictPosition = newValue;
            newDisPosition = newValue;
//            this.mCurrentDistrictName = ((String[])this.mDistrictDatasMap.get(this.mCurrentCityName))[newValue];
//            this.mCurrentZipCode = (String)this.mZipcodeDatasMap.get(this.mCurrentDistrictName);
        }
    }
}
